package com.isoftstone.spring.subject.mybatisplus;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 用户信息表 前端控制器
 */
@RestController
@RequestMapping("/api/users")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 创建用户 (POST /api/users)
     * @param user SysUser 对象
     * @return 创建成功的用户信息
     */
    @PostMapping
    public ResponseEntity<SysUser> createUser(@RequestBody SysUser user) {
        // 可以在这里添加创建时间等默认值
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        boolean isSaved = sysUserService.save(user);
        if (isSaved) {
            // 重新查询以获取生成的ID等信息
            SysUser savedUser = sysUserService.getById(user.getUserId());
            return ResponseEntity.ok(savedUser);
        } else {
            return ResponseEntity.status(500).build(); // 内部服务器错误
        }
    }

    /**
     * 根据ID获取用户 (GET /api/users/{id})
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<SysUser> getUserById(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取用户列表 (GET /api/users)
     * 支持分页和根据用户名模糊查询
     * @param page 页码 (从1开始)
     * @param size 每页大小
     * @param userName 用户名模糊查询
     * @return 用户列表分页数据
     */
    @GetMapping
    public ResponseEntity<IPage<SysUser>> listUsers(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String userName) {

        Page<SysUser> pageObj = new Page<>(page, size);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        if (userName != null && !userName.isEmpty()) {
            queryWrapper.like(SysUser::getUserName, userName);
        }
        // 只查询未删除的用户
        queryWrapper.eq(SysUser::getDelFlag, "0");

        IPage<SysUser> userPage = sysUserService.page(pageObj, queryWrapper);
        return ResponseEntity.ok(userPage);
    }


    /**
     * 更新用户 (PUT /api/users/{id})
     * @param id 用户ID
     * @param user 更新的用户信息
     * @return 更新后的用户信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<SysUser> updateUser(@PathVariable Long id, @RequestBody SysUser user) {
        SysUser existingUser = sysUserService.getById(id);
        if (existingUser == null) {
            return ResponseEntity.notFound().build();
        }
        // 确保ID一致
        user.setUserId(id);
        // 更新时间
        user.setUpdateTime(new Date());
        // 保留创建时间和创建者信息
        user.setCreateTime(existingUser.getCreateTime());
        user.setCreateBy(existingUser.getCreateBy());

        boolean isUpdated = sysUserService.updateById(user);
        if (isUpdated) {
            SysUser updatedUser = sysUserService.getById(id);
            return ResponseEntity.ok(updatedUser);
        } else {
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 删除用户 (DELETE /api/users/{id})
     * 这里实现逻辑删除
     * @param id 用户ID
     * @return 无内容
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        SysUser existingUser = sysUserService.getById(id);
        if (existingUser == null) {
            return ResponseEntity.notFound().build();
        }
        // 逻辑删除：更新 del_flag 字段
        SysUser userToDelete = new SysUser();
        userToDelete.setUserId(id);
        userToDelete.setDelFlag("2"); // 设置为已删除
        userToDelete.setUpdateTime(new Date());
        boolean isDeleted = sysUserService.updateById(userToDelete);
        if (isDeleted) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.status(500).build();
        }
    }

    @GetMapping("/findByName")
    public ResponseEntity<List<SysUser>> findUsers(@RequestParam("userName") String userName) {
        List<SysUser> userPage = sysUserService.findByName(userName);
        return ResponseEntity.ok(userPage);
    }
}
